//
//  MyWebView.m
//  HuiJu
//
//  Created by 纪翀 on 16/1/7.
//  Copyright © 2016年 恒宇博基. All rights reserved.
//

#import "MyWebView.h"
#import "CustomMoviePlayerController.h"
#import "UIButton+WebCache.h"
#import "Reachability.h"

@implementation MyWebView
{
    NSPredicate * _pred;
    NSDictionary *_detailDic;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/


-(void)playMovie:(NSString*)origFile{


    
    MyButton *playBtn = [MyButton buttonWithType: UIButtonTypeRoundedRect];
    playBtn.btnId = origFile;
    [playBtn setFrame:CGRectMake(0,0, self.frame.size.width, MIN(self.frame.size.height, WIN_B.frame.size.height))];
    [playBtn setTitle:[NSString stringWithFormat: @"点击播放《%@》", [_detailDic objectForKey:@"title"]] forState:UIControlStateNormal];
//    [playBtn setImage:@"mydownload_start.png" forState:UIControlStateNormal];
    [playBtn addTarget:self action:@selector(play:) forControlEvents:UIControlEventTouchUpInside];

    [self addSubview:playBtn];
}

-(void)play:(MyButton*)sender{
    Reachability *wifiReachability = [Reachability reachabilityForLocalWiFi];
    if ([wifiReachability currentReachabilityStatus] == NotReachable){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"目前wifi无法使用，确定继续访问吗？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            
        }];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
            CustomMoviePlayerController *playvc = [[CustomMoviePlayerController alloc]initWithVideo:sender.btnId detailDic:_detailDic];
            UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
            [appRootVC presentViewController:playvc animated:YES completion:^{}];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:okAction];
        UINavigationController *rootView = [[[UIApplication sharedApplication] keyWindow]rootViewController];
        [rootView presentViewController:alertController animated:YES completion:nil];
    }
    else{
        CustomMoviePlayerController *playvc = [[CustomMoviePlayerController alloc]initWithVideo:sender.btnId detailDic:_detailDic];
        UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
        [appRootVC presentViewController:playvc animated:YES completion:^{}];
    }

}


-(void)loadContent:(NSDictionary*)listDic detailDic:(NSDictionary*)detailDic{
    _detailDic = detailDic;
    NSString* content = [_detailDic objectForKey:@"content"];
    int contentType = [[_detailDic objectForKey:@"contenttype"] intValue];
    NSString* origFile = [_detailDic objectForKey:@"origfile"];
    _contentType = contentType;
    
    _pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", @"(?im).*\\.(mp4)$"];
    
    
    // 如果是Mp4则用CustomMoviePlayerController播放

    
    if (contentType == 1 && (origFile !=nil && ![origFile isEqualToString:@""])){
        BOOL isMatch  = [_pred evaluateWithObject:origFile];
        if (isMatch)
        {
            [self playMovie:origFile];
            return;
        }
        
        NSURLRequest  *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[origFile stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
        [self loadRequest:request];
        [self setCookie];
        
    }else if (contentType == 1 || contentType == 3) {
        
        NSURLRequest  *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[content stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
        [self loadRequest:request];
        [self setCookie];
    }
    else
    {
        [self loadHTMLString:content baseURL:nil];
    }
}

- (void)setCookie{
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:@"KeyCookies"];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
}


-(void)adjustLayout{
    //只有祼HTML的时候才进行调节
    if (_contentType == 2){
        [self stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '300%'"];
    }
}

@end
